package com.daguchuangyi.erp_android.productlist.select;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.daguchuangyi.erp_android.R;
import com.daguchuangyi.erp_android.base.CompatStatusBarActivity;
import com.daguchuangyi.erp_android.manager.NetworkManager;
import com.daguchuangyi.erp_android.manager.ParameterManager;
import com.daguchuangyi.erp_android.manager.networkservice.ProductService;
import com.daguchuangyi.erp_android.model.product.Product;
import com.daguchuangyi.erp_android.productlist.ProductSummaryManager;
import com.daguchuangyi.erp_android.productlist.classifiaction.ClassificationManager;
import com.daguchuangyi.erp_android.productlist.parametersetting.ParamsSettingDialog;
import com.daguchuangyi.erp_android.util.ErrorHandler;
import com.jude.utils.JUtils;
import com.kaopiz.kprogresshud.KProgressHUD;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class SelectProductActivity extends CompatStatusBarActivity implements ParameterManager.OnParamsChangeListener, ProductSummaryManager.OnProductCheckChangeListenner {

    private RecyclerView mRecyclerView;
    private GroupProductAdapter mGroupProductAdapter;

    private boolean mIsOnTopStack = false;

    private KProgressHUD hubDialog;
//            = KProgressHUD.create(this)
//            .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
//            .setCancellable(false)
//            .setAnimationSpeed(2)
//            .setDimAmount(0.5f)


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_product);
        setImmersiveStatusBar(false, Color.parseColor("#192b56"));

        findViewById(R.id.back_icon_iv).setOnClickListener(v -> finish());
        findViewById(R.id.delete_iv).setOnClickListener(v -> {
            ConfirmDeleteDialog deleteDialog = new ConfirmDeleteDialog();
            deleteDialog.setOnDeleteChooseListener(new ConfirmDeleteDialog.OnDeleteChooseListener() {
                @Override
                public void onDeleteConfirm() {
                    ProductSummaryManager.getInstance().removeAllProductChecked();
                    mGroupProductAdapter.setNewData(null);
                }

                @Override
                public void onDeleteCancel() {

                }
            });
            getSupportFragmentManager().beginTransaction()
                    .add(deleteDialog, "deleteDialog")
                    .commitAllowingStateLoss();
//            deleteDialog.show(getSupportFragmentManager(), "deleteDialog");
        });

        findViewById(R.id.setting_iv).setOnClickListener(v -> {
//            JUtils.Toast("展示设置页面");
            ParamsSettingDialog paramsSettingDialog = new ParamsSettingDialog();
            getSupportFragmentManager().beginTransaction()
                    .add(paramsSettingDialog, "paramsDialog")
                    .commitAllowingStateLoss();
//            paramsSettingDialog.show(getSupportFragmentManager(), "paramsDialog");
        });

        mRecyclerView = (RecyclerView) findViewById(R.id.group_produt_rv);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mGroupProductAdapter = new GroupProductAdapter(R.layout.item_group_product_layout, null);
        mRecyclerView.setAdapter(mGroupProductAdapter);

        DividerItemDecoration divider = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(this, R.drawable.group_product_divider));
        mRecyclerView.addItemDecoration(divider);

        ParameterManager.getInstance().addOnParamsChangeListener(this);

        loadData();

        ProductSummaryManager.getInstance().addProductCheckChangeListener(this);
    }

    @Override
    protected void onResume() {
        mIsOnTopStack = true;
        super.onResume();
    }

    @Override
    protected void onPause() {
        mIsOnTopStack = false;
        super.onPause();
    }

    private void loadData() {
//        List<GroupProductModel> groups = new ArrayList<>();
        hubDialog = KProgressHUD.create(this)
                .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                .setCancellable(false)
                .setAnimationSpeed(2)
                .setDimAmount(0.5f)
                .show();
        Observable.just(ProductSummaryManager.getInstance().getCheckedProudctIdList())
                .flatMap(integers -> {
                    List<Integer> ids = new ArrayList<>();
                    ids.addAll(integers);
                    return mapIdsToProducts(ids);
                })
                .doOnNext(products -> ClassificationManager.getInstance().loadClassificationInfo(false)
                        .toBlocking()
                        .subscribe())
                .flatMap(products1 -> {
                    HashMap<String, List<Product>> productMap = new HashMap<>();
                    for (Product item : products1) {
                        String id = item.getCategoryId();
                        if (productMap.containsKey(id)) {
                            productMap.get(id).add(item);
                        } else {
                            List<Product> productList = new ArrayList<>();
                            productList.add(item);
                            productMap.put(id, productList);
                        }
                    }
                    List<GroupProductModel> groupProductModels = new ArrayList<>();
                    Set<String> keys = productMap.keySet();
                    for (String id : keys) {
                        GroupProductModel group = new GroupProductModel();
                        group.setCategoryId(id);
                        group.setSubModels(productMap.get(id));
                        groupProductModels.add(group);
                    }

                    return Observable.just(groupProductModels);
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        groupProductModels -> mGroupProductAdapter.setNewData(groupProductModels),
                        throwable -> {
                            ErrorHandler.handlerNetworError(throwable, "加载失败，请检查网络状态");
                            if (hubDialog != null) {
                                hubDialog.dismiss();
                            }
                        },
                        () -> {
                            if (hubDialog != null) {
                                hubDialog.dismiss();
                            }
                        });
    }

    private Observable<List<Product>> mapIdsToProducts(List<Integer> ids) {
        return Observable.just(ids)
                .flatMap(integers -> {
                    List<Product> products = new ArrayList<>();
                    int groupCount = integers.size() / 10 + (integers.size() % 10 == 0 ? 0 : 1);
                    JUtils.Log("groupCount is : " + groupCount);
                    for (int i = 1; i <= groupCount; i++) {
                        Map<String, Object> bodymap = new HashMap<>();
                        bodymap.put("ids", integers);
                        Map<String, Object> innerMap = new HashMap<>();
                        innerMap.put("page", i);
                        bodymap.put("page", i);
                        NetworkManager.getInstance().getRetrofit().create(ProductService.class)
                                .listProductInfo(innerMap, bodymap)
                                .toBlocking()
                                .subscribe(productListWrapper -> products.addAll(productListWrapper.getProducts()),
                                        throwable -> ErrorHandler.handlerNetworError(throwable, "获取商品信息失败，请检查网络状态"));
                    }
                    return Observable.just(products);
                });
    }

    @Override
    protected void onDestroy() {
        ParameterManager.getInstance().removeOnParamsChangeListener(this);
        ProductSummaryManager.getInstance().removeProductCheckChangeListener(this);
        super.onDestroy();
    }

    @Override
    public void onParamChanged() {
        loadData();
    }

    @Override
    public void OnProductCheckChanged(int count) {
        if (!mIsOnTopStack) {
            loadData();
        }
    }
}
